﻿<link rel="stylesheet" href="/admin/assets/module/formSelects/formSelects-v4.css"/>
<style>
    .layui-badge-rim + .layui-badge-rim {
        margin-left: 5px;
    }
    .userForm .layui-form-label {
        width: 110px;
    }
    .userForm .layui-input-block {
        margin-left: 140px;
    }
    .cardU{
        background-image: url(../../../admin/assets/images/card_u.png);
        background-repeat: no-repeat;
        background-position: center;
        width: calc(100% - 142px);
        height: 150px;
        padding: 0;
    }
    .cardU img{width: 100%;height: 100%;}
    .import {
        opacity: 0;
        position: absolute;
        width: 69px;
        height: 38px;
        margin-left: -20px;
        cursor: pointer;
    }
</style>
<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-card-body">
            <div class="layui-form lay-header">
                <div class="toolbar">
                    <div class="layui-form-item lay-query-content">
                        <div class="lay-query-box">
                            <div class="query-lt">
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">部门：</label>
                                    <div class="layui-input-inline">
                                        <select name="departmentId" lay-filter="getDepartment" lay-search></select>
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">岗位：</label>
                                    <div class="layui-input-inline">
                                        <select name="postId" lay-search></select>
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">工号：</label>
                                    <div class="layui-input-inline">
                                        <input name="username" class="layui-input" type="text" placeholder="请输入工号"/>
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">姓名：</label>
                                    <div class="layui-input-inline">
                                        <input name="nickname" class="layui-input" type="text" placeholder="请输入姓名"/>
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">手机号：</label>
                                    <div class="layui-input-inline">
                                        <input name="phone" class="layui-input" type="text" placeholder="请输入手机号"/>
                                    </div>
                                </div>
                                <div class="layui-inline">
                                    <label class="layui-form-label w-auto">身份证：</label>
                                    <div class="layui-input-inline">
                                        <input name="idCard" class="layui-input" type="text" placeholder="请输入身份证"/>
                                    </div>
                                </div>
                            </div>
                            <div class="query-rt">
                                <div class="layui-inline">
                                    <button id="userBtnSearch" class="layui-btn icon-btn color-green">查询</button>
                                    <button class="layui-btn icon-btn color-white" lay-filter="resets" lay-submit>重置</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="lay-btn-rows">
                    <div class="lay-btn-box">
                        <div class="lay-btn-lt">
                            <button id="userBtnAdd" class="layui-btn icon-btn color-reseda">添加</button>
                        </div>
                        <div class="lay-btn-rt">
                            <button id="userBtnTemplate" class="layui-btn icon-btn layui-btn-normal">模板下载</button>
                            <button id="userBtnImport" class="layui-btn icon-btn color-reseda">
                                <input id="uploaderInput" type="file" name="file" class="import" accept=".xls,.xlsx"/>导入
                            </button>
                            <button id="userBtnExport" class="layui-btn icon-btn color-green">导出</button>
                        </div>
                    </div>
                </div>
            </div>
            <table class="layui-table" id="userTable" lay-filter="userTable"></table>
        </div>
    </div>

</div>

<!-- 表格操作列 -->
<script type="text/html" id="userTableBar">
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="reset">重置密码</a>
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="edit">修改</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
<!--    <a class="layui-btn layui-btn-xs" lay-event="auth">权限</a>-->
</script>
<!-- 表格状态列 -->
<script type="text/html" id="userTbaleState">
    <input type="checkbox" lay-filter="ckState" lay-skin="switch" lay-text="正常|锁定"
           value="{{d.id}}" {{d.status==1?'checked':''}}/>
</script>
<!-- 表格状态列 -->
<script type="text/html" id="userTbaleHasSettingRole">
    <input type="checkbox" lay-filter="ckHasSettingRole" lay-skin="switch" lay-text="开启|关闭"
           value="{{d.id}}" {{d.hasSettingRole?'checked':''}}/>
</script>
<script type="text/html" id="tableStateSex">
    {{d.sex==0?'女':'男'}}
</script>
<!-- 表单弹窗 -->
<script type="text/html" id="userForm">
    <form lay-filter="userForm" class="layui-form open-form userForm">
        <input name="id" type="hidden"/>
        <div class="open-model">
            <div class="open-auto">
                <div class="layui-col-xs6">
                    <div class="layui-form-item">
                        <label class="layui-form-label"><span style="color: red">*</span>所属企业</label>
                        <div class="layui-input-block">
                            <select name="companyInfoId" lay-filter="getCompanyInfo" lay-verify="required" required lay-search></select>
                        </div>
                    </div>
                </div>
                <div class="layui-col-xs6">
                    <div class="layui-form-item">
                        <label class="layui-form-label"><span style="color: red">*</span>所属部门</label>
                        <div class="layui-input-block">
                            <select name="departmentId" lay-filter="getDepartment" lay-verify="required" required lay-search></select>
                        </div>
                    </div>
                </div>
                <div class="layui-col-xs6">
                    <div class="layui-form-item">
                        <label class="layui-form-label"><span style="color: red">*</span>选择岗位</label>
                        <div class="layui-input-block">
                            <select name="postId" lay-filter="getPost" lay-verify="required" required lay-search></select>
                        </div>
                    </div>
                </div>
                <div class="layui-col-xs6">
                    <div class="layui-form-item">
                        <label class="layui-form-label">职务</label>
                        <div class="layui-input-block">
                            <select name="positionId" lay-search></select>
                        </div>
                    </div>
                </div>
                <div class="layui-col-xs6">
                    <div class="layui-form-item">
                        <label class="layui-form-label"><span style="color: red">*</span>用户名(工号)</label>
                        <div class="layui-input-block">
                            <input name="username" placeholder="请输入工号" type="text" class="layui-input"
                                   maxlength="20" lay-verify="required|isOnlyUsername" required/>
                        </div>
                    </div>
                </div>
                <div class="layui-col-xs6">
                    <div class="layui-form-item">
                        <label class="layui-form-label"><span style="color: red">*</span>姓名</label>
                        <div class="layui-input-block">
                            <input name="nickname" placeholder="请输入姓名" type="text" class="layui-input"
                                   maxlength="20" lay-verify="required" required/>
                        </div>
                    </div>
                </div>
                <div class="layui-col-xs6">
                    <div class="layui-form-item">
                        <label class="layui-form-label"><span style="color: red">*</span>手机号</label>
                        <div class="layui-input-block">
                            <input name="phone" placeholder="请输入手机号" type="text" class="layui-input"
                                   lay-verify="required|phone|isOnlyPhone" required/>
                        </div>
                    </div>
                </div>
                <div class="layui-col-xs6">
                    <div class="layui-form-item">
                        <label class="layui-form-label"><span style="color: red">*</span>性别</label>
                        <div class="layui-input-block">
                            <input type="radio" name="sex" value="1" title="男" checked/>
                            <input type="radio" name="sex" value="0" title="女"/>
                        </div>
                    </div>
                </div>
                <div class="layui-col-xs6">
                    <div class="layui-form-item">
                        <label class="layui-form-label">身份证号</label>
                        <div class="layui-input-block">
                            <input name="idCard" placeholder="请输入身份证号" type="text" class="layui-input" maxlength="18" lay-verify="idCard" />
                        </div>
                    </div>
                </div>
                <div class="layui-col-xs6">
                    <div class="layui-form-item">
                        <label class="layui-form-label">入职时间</label>
                        <div class="layui-input-block">
                            <input name="entryTime" id="entryTime" placeholder="请输入入职时间" readonly type="text" class="layui-input" />
                        </div>
                    </div>
                </div>
                <div class="layui-col-xs6">
                    <div class="layui-form-item">
                        <label class="layui-form-label">邮箱</label>
                        <div class="layui-input-block">
                            <input name="email" placeholder="请输入邮箱" type="text" class="layui-input" maxlength="200" />
                        </div>
                    </div>
                </div>
                <div class="layui-col-xs6">
                    <div class="layui-form-item">
                        <label class="layui-form-label">工资卡开户行</label>
                        <div class="layui-input-block">
                            <input name="bank" placeholder="请输入工资卡开户行" type="text" class="layui-input" maxlength="200" />
                        </div>
                    </div>
                </div>
                <div class="layui-col-xs6">
                    <div class="layui-form-item">
                        <label class="layui-form-label">工资卡账号</label>
                        <div class="layui-input-block">
                            <input name="account" placeholder="请输入工资卡账号" type="text" class="layui-input" maxlength="200" />
                        </div>
                    </div>
                </div>
                <div class="layui-col-xs6">
                    <div class="layui-form-item">
                        <label class="layui-form-label">生日</label>
                        <div class="layui-input-block">
                            <input name="birthday" id="birthday" placeholder="请输入生日" readonly type="text" class="layui-input" />
                        </div>
                    </div>
                </div>
                <div class="layui-form-item">
                    <div class="layui-col-xs6">
                        <label class="layui-form-label">在职状态</label>
                        <div class="layui-input-block">
                            <select name="isJob">
                                <option value="job">在职</option>
                                <option value="resign">离职</option>
                                <option value="retire">退休</option>
                            </select>
                        </div>
                    </div>
                    <div class="layui-col-xs6">
                        <label class="layui-form-label">所属主柜</label>
                        <input name="cabinet" type="hidden"/>
                        <div class="layui-input-block" id="cabinet"></div>
                    </div>
                </div>
                <!--        <div class="layui-form-item">-->
                <!--            <label class="layui-form-label">柜子权限</label>-->
                <!--            <div class="layui-input-block" id="cabinetAuthorityBox">-->
                <!--                <input type="checkbox" name="cabinetAuthority" lay-skin="primary" title="小程序" value="1">-->
                <!--                <input type="checkbox" name="cabinetAuthority" lay-skin="primary" title="取刀还刀" value="2">-->
                <!--                <input type="checkbox" name="cabinetAuthority" lay-skin="primary" title="收刀" value="3">-->
                <!--                <input type="checkbox" name="cabinetAuthority" lay-skin="primary" title="调试" value="4">-->
                <!--                <input type="checkbox" name="cabinetAuthority" lay-skin="primary" title="暂存" value="5">-->
                <!--                <input type="checkbox" name="cabinetAuthority" lay-skin="primary" title="柜机账号" value="6">-->
                <!--            </div>-->
                <!--        </div>-->
                <div class="layui-col-xs6" style="height: 170px;">
                    <div class="layui-form-item">
                        <label class="layui-form-label">人脸识别头像</label>
                        <div class="layui-upload-drag cardU" id="headerImg">
                            <!--<i class="layui-icon"></i>
                            <p>点击上传，或将文件拖拽到此处</p>-->
                            <input type="hidden" name="headerImg" lay-verify="" data-name="头像" >
                        </div>
                    </div>
                </div>
                <div class="layui-col-xs6" style="height: 170px;">
                    <div class="layui-form-item">
                        <label class="layui-form-label">银行卡照片</label>
                        <div class="layui-upload-drag cardU" id="bankCardPhoto">
                            <!--<i class="layui-icon"></i>
                            <p>点击上传，或将文件拖拽到此处</p>-->
                            <input type="hidden" name="bankCardPhoto" lay-verify="" data-name="银行卡照片" >
                        </div>
                    </div>
                </div>
                <div class="layui-col-xs6" style="height: 170px;">
                    <div class="layui-form-item">
                        <label class="layui-form-label">身份证正面照</label>
                        <div class="layui-upload-drag cardU" id="frontPhoto">
                            <!--<i class="layui-icon"></i>
                            <p>点击上传，或将文件拖拽到此处</p>-->
                            <input type="hidden" name="frontPhoto" lay-verify="" data-name="身份证正面照" >
                        </div>
                    </div>
                </div>
                <div class="layui-col-xs6" style="height: 170px;">
                    <div class="layui-form-item">
                        <label class="layui-form-label">身份证背面照</label>
                        <div class="layui-upload-drag cardU" id="backPhoto">
                            <!--<i class="layui-icon"></i>
                            <p>点击上传，或将文件拖拽到此处</p>-->
                            <input type="hidden" name="backPhoto" lay-verify="" data-name="身份证背面照" >
                        </div>
                    </div>
                </div>

                <div class="layui-form-item">
                    <label class="layui-form-label" style="width: 100px">薪资福利设置</label>
                </div>
                <div class="layui-col-xs6">
                    <div class="layui-form-item">
                        <label class="layui-form-label">社保基数</label>
                        <div class="layui-input-block">
                            <input id="socialSecurityBase" name="socialSecurityBase" placeholder="社保基数" type="text" maxlength="10" class="layui-input" lay-verify="integer" />
                        </div>
                    </div>
                </div>
                <div class="layui-col-xs6">
                    <div class="layui-form-item">
                        <label class="layui-form-label">社保始缴月</label>
                        <div class="layui-input-block">
                            <input id="startMonthSocialSecurity" name="startMonthSocialSecurity" placeholder="社保始缴月" readonly type="text" class="layui-input" />
                        </div>
                    </div>
                </div>
                <div class="layui-col-xs6">
                    <div class="layui-form-item">
                        <label class="layui-form-label">公积金基数</label>
                        <div class="layui-input-block">
                            <input id="providentFundBase" name="providentFundBase" placeholder="公积金基数" type="text" maxlength="10"  class="layui-input" lay-verify="integer" />
                        </div>
                    </div>
                </div>
                <div class="layui-col-xs6">
                    <div class="layui-form-item">
                        <label class="layui-form-label">公积金始缴月</label>
                        <div class="layui-input-block">
                            <input id="startMonthProvidentFund" name="startMonthProvidentFund" placeholder="公积金始缴月" readonly type="text" class="layui-input" />
                        </div>
                    </div>
                </div>
                <!--<div class="layui-form-item">
                    <label class="layui-form-label">角色</label>
                    <div class="layui-input-block">
                        <select name="roleId" xm-select="selRole" xm-select-skin="default" lay-verify="required"></select>
                    </div>
                </div>-->
            </div>
            <div class="layui-form-item text-right">
                <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
                <button class="layui-btn" lay-filter="userFormSubmit" lay-submit>保存</button>
            </div>
        </div>
    </form>
</script>
<!-- 接口权限 -->
<script type="text/html" id="authModel">
    <form lay-filter="roleAuthorityForm" class="layui-form model-form">
        <input name="id" type="hidden"/>
        <div class="layui-form-item open-details-box">
            <label class="layui-form-label">选择权限</label>
            <div class="layui-input-block">
                <div id="LAY-auth-tree-index"></div>
            </div>
        </div>
        <div class="layui-form-item text-right">
            <button class="layui-btn layui-btn-primary" type="button" ew-event="closeDialog">取消</button>
            <button class="layui-btn" lay-filter="roleAuthorityFormSubmit" lay-submit>保存</button>
        </div>
    </form>
</script>

<script type="text/javascript" src="../../../admin/assets/js/jsencrypt.min.js"></script>
<script>
    layui.use(['layer', 'form', 'table', 'util', 'formSelects', 'admin', 'config', 'upload', 'laydate'], function () {
        var $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        var table = layui.table;
        var util = layui.util;
        var formSelects = layui.formSelects;
        var admin = layui.admin;
        var config = layui.config;
        var upload = layui.upload;
        var laydate = layui.laydate;
        var mRoles = [];  // 全部角色

        form.render('select');

        // 获取部门数据
        admin.req('user/admin/department/list', {limit:9999}, function (res) {
            if ( res.code==200) {
                var html='<option value="">请选择部门</option>';
                for(var k=0;k<res.data.length;k++){
                    html+='<option value="'+res.data[k].id+'">'+res.data[k].name+'</option>';
                }
                $("select[name='departmentId']").html(html);
                form.render('select');
                form.on('select(getDepartment)',function (data) {
                    if(data.value){
                        // 获取岗位数据
                        admin.req('user/admin/role/list', {limit:9999, departmentId: data.value}, function (res) {
                            if (res.code==200) {
                                var html='<option value="">请选择岗位</option>';
                                for(var k=0;k<res.data.length;k++){
                                    html+='<option value="'+res.data[k].id+'">'+res.data[k].name+'</option>';
                                }
                                $("select[name='postId']").html(html);
                                form.render('select');
                            } else {
                                layer.msg('获取岗位失败', {icon: 2, time: 1000});
                            }
                        }, 'GET');
                    }else{
                        $("select[name='postId']").html("");
                        form.render('select');
                    }
                })
            } else {
                layer.msg('获取部门失败', {icon: 2, time: 1000});
            }
        }, 'GET');

        // 渲染表格
        var insTb = table.render({
            elem: '#userTable',
            url: config.base + 'user/admin/user/list',
            page: true,
            cellMinWidth: 100,
            cols: [[
                {type: 'numbers'},
                {field: 'username', title: '用户名(工号)'},
                {field: 'nickname', title: '姓名'},
                {field: 'phone', title: '手机号'},
                {field: 'sex', title: '性别', templet: '#tableStateSex'},
                {field: 'companyInfoName', sort: true, title: '企业'},
                {field: 'departmentName', sort: true, title: '部门'},
                {
                    templet: function (d) {
                        var str = '';
                        for (var i = 0; i < d.roles.length; i++) {
                            str += ('<span class="layui-badge-rim">' + d.roles[i].name + '</span>');
                        }
                        return str;
                    }, title: '角色'
                },
                {field: 'createTime', sort: true, title: '创建时间'},
                {field: 'state', templet: '#userTbaleState', title: '状态', unresize: true, width: 100},
                {field: 'hasSettingRole', templet: '#userTbaleHasSettingRole', title: '柜子面板权限', unresize: true, width: 120},
                {align: 'center', toolbar: '#userTableBar', title: '操作', unresize: true, width: 200}
            ]],
            done: function (res, curr, count) {
                //移除按钮
                var menuButton = config.getMenuButton(location.hash);
                if(menuButton.indexOf("搜索") == -1){
                    $('.layui-form.toolbar').remove();
                }
                if(menuButton.indexOf("重置密码") == -1){
                    $("[lay-event='reset']").remove();
                }
                if(menuButton.indexOf("修改") == -1){
                    $("[lay-event='edit']").remove();
                }
                if(menuButton.indexOf("删除") == -1){
                    $("[lay-event='del']").remove();
                }
            }
        });

        // 搜索按钮点击事件
        $('#userBtnSearch').click(function () {
            var key = $('#userSltKey').val();
            var value = $('#userEdtSearch').val();
            var departmentId = $('select[name=departmentId]').val();
            var postId = $('select[name=postId]').val();
            var username = $('input[name=username]').val();
            var nickname = $('input[name=nickname]').val();
            var phone = $('input[name=phone]').val();
            var idCard = $('input[name=idCard]').val();
            insTb.reload({where: {searchKey: key, searchValue: value, departmentId: departmentId, postId: postId, username: username
                    , nickname: nickname, phone: phone, idCard: idCard}, page:{curr:1}}, 'data');
        });

        // 重置搜索
        form.on('submit(resets)', function (data) {
            $(".lay-header").find('select').val("");
            $(".lay-header").find('input').val("");
            let field = data.field;
            for (let key in field) {
                field[key] = ''
            }
            insTb.reload({where: field, page: {curr: 1}}, 'data');
        });

        // 添加按钮点击事件
        $('#userBtnAdd').click(function () {
            showEditModel();
        });

        // 工具条点击事件
        table.on('tool(userTable)', function (obj) {
            var data = obj.data;
            var layEvent = obj.event;

            if (layEvent === 'del') { // 删除
                layer.confirm('确定删除此用户吗？', {
                    skin: 'layui-layer-admin'
                }, function (i) {
                    layer.close(i);
                    layer.load(2);
                    admin.req('user/admin/user/' + obj.data.id, {}, function (data) {
                        layer.closeAll('loading');
                        if (data.code == 200) {
                            layer.msg(data.msg, {icon: 1});
                            obj.del();
                        } else {
                            layer.msg(data.msg, {icon: 2});
                        }
                    }, 'DELETE');
                });
            } else if (layEvent === 'reset') { // 重置密码
                layer.confirm('确定重置此用户的密码吗？<br><span style="color: red;">（初始密码为123456）</span>', {
                    skin: 'layui-layer-admin'
                }, function (i) {
                    layer.close(i);
                    layer.load(2);
                    admin.req('user/admin/user/resetPassword', {id: obj.data.id}, function (data) {
                        layer.closeAll('loading');
                        if (data.code == 200) {
                            layer.msg(data.msg, {icon: 1});
                        } else {
                            layer.msg(data.msg, {icon: 2});
                        }
                    }, 'PUT');
                });
            } else if (layEvent === 'edit') { // 修改
                showEditModel(data);
            } else if (obj.event === 'auth') {  // 权限管理
                showPermDialog(obj.data);
            }
        });

        // 修改user状态
        form.on('switch(ckState)', function (obj) {
            layer.load(2);
            admin.req('oauth2/admin/user/updateStatus', {
                userId: obj.elem.value,
                status: obj.elem.checked ? 1 : 0
            }, function (data) {
                layer.closeAll('loading');
                if (data.code == 200) {
                    layer.msg(data.msg, {icon: 1});
                } else {
                    layer.msg(data.msg, {icon: 2});
                    $(obj.elem).prop('checked', !obj.elem.checked);
                    form.render('checkbox');
                }
            }, 'PUT');
        });

        // 修改柜子面板权限
        form.on('switch(ckHasSettingRole)', function (obj) {
            layer.load(2);
            admin.req('user/admin/user/updateHasSettingRole', {
                userId: obj.elem.value,
                hasSettingRole: obj.elem.checked ? true : false
            }, function (data) {
                layer.closeAll('loading');
                if (data.code == 200) {
                    layer.msg(data.msg, {icon: 1});
                } else {
                    layer.msg(data.msg, {icon: 2});
                    $(obj.elem).prop('checked', !obj.elem.checked);
                    form.render('checkbox');
                }
            }, 'PUT');
        });

        // 显示表单弹窗
        function showEditModel(data) {
            admin.open({
                type: 1,
                area: ['60%', '850px'],
                offset: '65px',
                title: data ? '修改用户' : '添加用户',
                content: $('#userForm').html(),
                success: function (layero, index) {
                    form.render('select');
                    // $(layero).children('.layui-layer-content').css('overflow', 'visible');
                    form.render('radio');
                    form.render('checkbox');
                    //入职时间
                    laydate.render({
                        elem: '#entryTime'
                    });
                     //生日
                    laydate.render({
                        elem: '#birthday'
                    });
                    //社保始缴月
                    laydate.render({
                        elem: '#startMonthSocialSecurity'
                    });
                    //公积金始缴月
                    laydate.render({
                        elem: '#startMonthProvidentFund'
                    });

                    form.verify({
                        idCard: function(value, item){ //value：表单的值、item：表单的DOM对象
                            if(value != ""){
                                var city={11:"北京",12:"天津",13:"河北",14:"山西",15:"内蒙古",21:"辽宁",22:"吉林",23:"黑龙江 ",31:"上海",32:"江苏",33:"浙江",34:"安徽",35:"福建",36:"江西",37:"山东",41:"河南",42:"湖北 ",43:"湖南",44:"广东",45:"广西",46:"海南",50:"重庆",51:"四川",52:"贵州",53:"云南",54:"西藏 ",61:"陕西",62:"甘肃",63:"青海",64:"宁夏",65:"新疆",71:"台湾",81:"香港",82:"澳门",91:"国外 "};
                                if(!/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(value)){
                                    return '身份证号格式错误';
                                } else if (!city[value.substr(0,2)]){
                                    return '地址编码错误';
                                } else {
                                    //18位身份证需要验证最后一位校验位if(code.length == 18){
                                    value = value.split('');
                                    //∑(ai×Wi)(mod 11)//加权因子
                                    var factor = [ 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 ];
                                    //校验位
                                    var parity = [ 1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2 ];
                                    var sum = 0;
                                    var ai = 0;
                                    var wi = 0;
                                    for (var i = 0; i < 17; i++)
                                    {
                                        ai = value[i];
                                        wi = factor[i];
                                        sum += ai * wi;
                                    }
                                    var last = parity[sum % 11];
                                    if(parity[sum % 11] != value[17]){
                                        return '校验位错误';
                                    }
                                }
                            }
                        },
                        isOnlyUsername: function (value) {
                            var isOnly = true;
                            var idVal = $("form input[name='id']").val();
                            admin.req('user/admin/user/isOnly', {username:value,id:idVal}, function (res) {
                                if (res.code == 200) {
                                    isOnly = res.data;
                                }
                            }, 'GET',false);
                            if(!isOnly){
                                return "工号必须唯一"
                            }
                        },
                        isOnlyPhone: function (value) {
                            var isOnly = true;
                            var idVal = $("form input[name='id']").val();
                            admin.req('user/admin/user/isOnly', {phone:value,id:idVal}, function (res) {
                                if (res.code == 200) {
                                    isOnly = res.data;
                                }
                            }, 'GET',false);
                            if(!isOnly){
                                return "手机号必须唯一"
                            }
                        },
                        integer: [/^[0-9]\d*$/, '格式错误'],
                        mobile: [/^(1(3|4|5|7|8|9)\d{9}|[ \t]*)$/, '手机号码格式错误'],
                        headerImg: function (value, item) {
                            if(value == ""){
                                return "请上传"+$(item).data("name");
                            }
                        }
                    })

                    let cabinetData = []
                    admin.reqSync('enterprisecab/cabinet/admin/cabinet/getCabinetByCabinetNature', {limit:9999}, function (res) {

                        if ( res.code==200) {
                            res.data.forEach((item,index) => {
                                cabinetData.push({name:item.cabCode,value:item.id})
                            })
                        }
                    }, 'GET');

                    console.log(data)
                    // 选择主柜
                    xmSelect.render({
                        el: '#cabinet',
                        model: {label: {type: 'text'}},
                        filterable: true,
                        tips: '顶级分类',
                        height: 'auto',
                        initValue: data?data.cabinet.split(","):[],
                        data: cabinetData,
                        on: function (data) {
                            let cabinetValue = [];
                            if (data.arr.length>0){
                                data.arr.forEach(item=>{
                                    cabinetValue.push(item.value)
                                });
                                $("form[lay-filter='userForm'] input[name='cabinet']").val(cabinetValue.toString());
                            }else {
                                $("form[lay-filter='userForm'] input[name='cabinet']").val('');
                            }
                        },
                    });

                    if(data){
                        var frontPhoto = data.frontPhoto;
                        // let cabinetAuthoritArr = data.cabinetAuthority.split(',');
                        //
                        // if(cabinetAuthoritArr.indexOf('1') >=0 ){
                        //     data.cabinetAuthority= 1;
                        //
                        // }else {
                        //     data.cabinetAuthority = void 1;
                        // }

                        // $('#cabinetAuthorityBox input[type=checkbox]').each(function() {
                        //     if(cabinetAuthoritArr.indexOf($(this).val())>=0){
                        //         $(this).attr("checked","true")
                        //     }
                        //     form.render('checkbox');
                        // });

                        if(frontPhoto){
                            $("#frontPhoto").html('<img src="'+ frontPhoto+'" alt="上传成功后渲染" style="max-width: 196px"><input type="hidden" name="frontPhoto" value="'+frontPhoto+'">');
                        }
                        var backPhoto = data.backPhoto;
                        if(backPhoto){
                            $("#backPhoto").html('<img src="'+ backPhoto+'" alt="上传成功后渲染" style="max-width: 196px"><input type="hidden" name="backPhoto" value="'+backPhoto+'">');
                        }
                        var headerImg = data.headerImg;
                        if(headerImg){
                            $("#headerImg").html('<img src="'+ headerImg+'" alt="上传成功后渲染" style="max-width: 196px"><input type="hidden" name="headerImg" value="'+headerImg+'">');
                        }
                        var bankCardPhoto = data.bankCardPhoto;
                        if(bankCardPhoto){
                            $("#bankCardPhoto").html('<img src="'+ bankCardPhoto+'" alt="上传成功后渲染" style="max-width: 196px"><input type="hidden" name="bankCardPhoto" value="'+bankCardPhoto+'">');
                        }
                        // 在职状态
                        var isJobOption = $("form select[name='isJob']").find("option");
                        layui.each(isJobOption, function(index, item){
                            if(data.isJob == item.text){
                                data.isJob = item.value;
                            }
                        });

                    }

                    //拖拽上传身份证正面图片
                    upload.render({
                        elem: '#frontPhoto'
                        ,url: config.upload_url + 'upload?path='+img_path
                        , auto: true
                        , acceptMime: 'image/*'
                        ,headers:{authorization:'Bearer '+config.getToken()}
                        ,done: function(res){
                            if(res.code == 200){
                                layer.msg("上传成功", {icon: 1});
                                var imagUrl=res.data.url;
                                /*if(imagUrl){
                                    imagUrl=imagUrl.substring(imagUrl.indexOf('/')+1)
                                }*/
                                $("#frontPhoto").html('<img src="'+imagUrl+'" alt="上传成功后渲染" style="max-width: 196px"><input type="hidden" name="frontPhoto" value="'+imagUrl+'">');
                            }else if(res.code == 502){
                                return location.replace('admin/login.html');
                            }else{
                                layer.msg(res.msg, {icon: 2});
                            }
                        }
                    });

                    //拖拽上传身份证反面图片
                    upload.render({
                        elem: '#backPhoto'
                        ,url: config.upload_url + 'upload?path='+img_path
                        , auto: true
                        , acceptMime: 'image/*'
                        ,headers:{authorization:'Bearer '+config.getToken()}
                        ,done: function(res){
                            if(res.code == 200){
                                layer.msg("上传成功", {icon: 1});
                                var imagUrl=res.data.url;
                                /*if(imagUrl){
                                    imagUrl=imagUrl.substring(imagUrl.indexOf('/')+1)
                                }*/
                                $("#backPhoto").html('<img src="'+imagUrl+'" alt="上传成功后渲染" style="max-width: 196px"><input type="hidden" name="backPhoto" value="'+imagUrl+'">');
                            }else if(res.code == 502){
                                return location.replace('admin/login.html');
                            }else{
                                layer.msg(res.msg, {icon: 2});
                            }
                        }
                    });

                    //拖拽上传头像图片
                    upload.render({
                        elem: '#headerImg'
                        ,url: config.upload_url + 'upload?path='+img_path
                        , auto: true
                        , acceptMime: 'image/*'
                        ,headers:{authorization:'Bearer '+config.getToken()}
                        ,done: function(res){
                            if(res.code == 200){
                                layer.msg("上传成功", {icon: 1});
                                var imagUrl=res.data.url;
                                /*if(imagUrl){
                                    imagUrl=imagUrl.substring(imagUrl.indexOf('/')+1)
                                }*/
                                $("#headerImg").html('<img src="'+imagUrl+'" alt="上传成功后渲染" style="max-width: 196px"><input type="hidden" name="headerImg" value="'+imagUrl+'">');
                            }else if(res.code == 502){
                                return location.replace('admin/login.html');
                            }else{
                                layer.msg(res.msg, {icon: 2});
                            }
                        }
                    });

                    //拖拽上传银行卡照片
                    upload.render({
                        elem: '#bankCardPhoto'
                        ,url: config.upload_url + 'upload?path='+img_path
                        , auto: true
                        , acceptMime: 'image/*'
                        ,headers:{authorization:'Bearer '+config.getToken()}
                        ,done: function(res){
                            if(res.code == 200){
                                layer.msg("上传成功", {icon: 1});
                                var imagUrl=res.data.url;
                                /*if(imagUrl){
                                    imagUrl=imagUrl.substring(imagUrl.indexOf('/')+1)
                                }*/
                                $("#bankCardPhoto").html('<img src="'+imagUrl+'" alt="上传成功后渲染" style="max-width: 196px"><input type="hidden" name="bankCardPhoto" value="'+imagUrl+'">');
                            }else if(res.code == 502){
                                return location.replace('admin/login.html');
                            }else{
                                layer.msg(res.msg, {icon: 2});
                            }
                        }
                    });

                    // 渲染角色下拉框
                    /*var roleSelData = new Array();
                    for (var i = 0; i < mRoles.length; i++) {
                        roleSelData.push({name: mRoles[i].name, value: mRoles[i].id});
                    }
                    formSelects.data('selRole', 'local', {arr: roleSelData});
                    // 回显user数据
                    if (data) {
                        form.val('userForm', data);
                        var rds = new Array();
                        for (var i = 0; i < data.roles.length; i++) {
                            rds.push(data.roles[i].id);
                        }
                        formSelects.value('selRole', rds);  // 回显多选框
                    }*/

                    // 获取企业数据
                    admin.reqSync('user/admin/companyInfo/list', {limit:9999}, function (res) {
                        if ( res.code==200) {
                            var html='<option value="">请选择企业</option>';
                            for(var k=0;k<res.data.length;k++){
                                html+='<option value="'+res.data[k].id+'">'+res.data[k].name+'</option>';
                            }
                            $("form select[name='companyInfoId']").html(html);
                            form.render('select');
                            if(data && data.companyInfoId){
                                form.val('userForm', data);
                            }
                            form.on('select(getCompanyInfo)', function (res) {
                                if(res.value){
                                    // 获取部门数据
                                    admin.req('user/admin/department/list', {limit:9999, companyInfoId: res.value}, function (res) {
                                        if ( res.code==200) {
                                            var html='<option value="">顶级部门</option>';
                                            for(var k=0;k<res.data.length;k++){
                                                html+='<option value="'+res.data[k].id+'">'+res.data[k].name+'</option>';
                                            }
                                            $("form select[name='departmentId']").html(html);
                                            form.render('select');
                                            form.on('select(getDepartment)',function (res) {
                                                if(res.value){
                                                    // 获取岗位数据
                                                    admin.req('user/admin/role/list', {limit:9999, departmentId: res.value}, function (res) {
                                                        if (res.code==200) {
                                                            var html='<option value="">请选择岗位</option>';
                                                            for(var k=0;k<res.data.length;k++){
                                                                html+='<option value="'+res.data[k].id+'">'+res.data[k].name+'</option>';
                                                            }
                                                            $("form select[name='postId']").html(html);
                                                            form.render('select');
                                                            form.on('select(getPost)', function (resPost) {
                                                                if(resPost.value){
                                                                    for (var i = 0; i < res.data.length; i++) {
                                                                        if(res.data[i].id == resPost.value){
                                                                            $("#socialSecurityBase").val(res.data[i].socialSecurityBase);// 社保基数
                                                                            $("#providentFundBase").val(res.data[i].providentFundBase);// 公积金基数
                                                                        }
                                                                    }
                                                                }else{
                                                                    $("#socialSecurityBase").val("");// 社保基数
                                                                    $("#providentFundBase").val("");// 公积金基数
                                                                }
                                                            })
                                                        } else {
                                                            layer.msg('获取岗位失败', {icon: 2, time: 1000});
                                                        }
                                                    }, 'GET');
                                                }else{
                                                    $("form select[name='postId']").html("");
                                                    form.render('select');
                                                }
                                            })
                                        } else {
                                            layer.msg('获取部门失败', {icon: 2, time: 1000});
                                        }
                                    }, 'GET');
                                }else{
                                    $("form select[name='departmentId']").html("");
                                    $("form select[name='postId']").html("");
                                    form.render('select');
                                }
                            })
                        } else {
                            layer.msg('获取企业失败', {icon: 2, time: 1000});
                        }
                    }, 'GET');

                    // 获取职务
                    admin.req('user/admin/position/list', {limit:9999}, function (res) {
                        if (res.code==200) {
                            var html='<option value="">请选择职务</option>';
                            for(var k=0;k<res.data.length;k++){
                                html+='<option value="'+res.data[k].id+'">'+res.data[k].name+'</option>';
                            }
                            $("form select[name='positionId']").html(html);
                            form.render('select');
                            if(data && data.positionId){
                                form.val('userForm', data);
                            }
                        } else {
                            layer.msg('获取职务失败', {icon: 2, time: 1000});
                        }
                    }, 'GET');

                    if(data && data.companyInfoId){
                        // 获取部门数据
                        admin.reqSync('user/admin/department/list', {limit:9999, companyInfoId: data.companyInfoId}, function (res) {
                            if ( res.code==200) {
                                var html='<option value="">顶级部门</option>';
                                for(var k=0;k<res.data.length;k++){
                                    html+='<option value="'+res.data[k].id+'">'+res.data[k].name+'</option>';
                                }
                                $("form select[name='departmentId']").html(html);
                                form.render('select');
                                if(data && data.departmentId){
                                    form.val('userForm', data);
                                }
                            } else {
                                layer.msg('获取部门失败', {icon: 2, time: 1000});
                            }
                        }, 'GET');
                    }

                    if(data && data.departmentId){
                        // 获取岗位数据
                        admin.reqSync('user/admin/role/list', {limit:9999, departmentId: data.departmentId}, function (res) {
                            if (res.code==200) {
                                var html='<option value="">请选择岗位</option>';
                                for(var k=0;k<res.data.length;k++){
                                    html+='<option value="'+res.data[k].id+'">'+res.data[k].name+'</option>';
                                }
                                $("form select[name='postId']").html(html);
                                form.render('select');
                                if(data && data.postId){
                                    form.val('userForm', data);
                                }
                            } else {
                                layer.msg('获取岗位失败', {icon: 2, time: 1000});
                            }
                        }, 'GET');
                    }


                    // 表单提交事件
                    form.on('submit(userFormSubmit)', function (d) {
                        // d.field.roleIds = formSelects.value('selRole', 'valStr');
                        //let cabinetAuthorityArray = [];
                        // $('#cabinetAuthorityBox input[type=checkbox]:checked').each(function() {
                        //     cabinetAuthorityArray.push($(this).val());
                        // });
                        console.log(d.field)
                        //d.field.cabinetAuthority = cabinetAuthorityArray.toString();
                        d.field.roleIds = d.field.postId;
                        layer.load(2);
                        if(d.field.entryTime){
                            d.field.entryTime = d.field.entryTime + " 00:00:00";
                        }
                        if(d.field.birthday){
                            d.field.birthday = d.field.birthday + " 00:00:00";
                        }
                        if(d.field.startMonthSocialSecurity){
                            d.field.startMonthSocialSecurity = d.field.startMonthSocialSecurity + " 00:00:00";
                        }
                        if(d.field.startMonthProvidentFund){
                            d.field.startMonthProvidentFund = d.field.startMonthProvidentFund + " 00:00:00";
                        }

                        admin.req(data ? 'user/admin/user/update' : 'user/admin/user/add', d.field, function (res) {
                            layer.closeAll('loading');
                            if (res.code == 200) {
                                layer.msg(res.msg, {icon: 1});
                                layer.closeAll('page');
                                table.reload('userTable');
                            } else {
                                layer.msg(res.msg, {icon: 2});
                            }
                        }, data ? 'PUT' : 'POST');
                        return false;
                    });
                }
            });
        }

        // 获取所有角色
        admin.req('user/admin/role/list', {}, function (res) {
            layer.closeAll('loading');
            if (200 == res.code) {
                mRoles = res.data;
            } else {
                layer.msg('获取角色失败', {icon: 2});
            }
        }, 'GET');

        // 权限管理
        function showPermDialog(data) {
            admin.open({
                type: 1,
                isDetail: true,
                area: '800px',
                offset: '65px',
                title: '角色权限管理',
                content: $('#authModel').html(),
                success: function () {

                    admin.req('user/admin/menu/authTree', {roleId: data.id}, function (res) {
                        layer.closeAll('loading');
                        if (res.code == 200) {
                            var trees = res.data;
                            authtree.render('#LAY-auth-tree-index', trees, {
                                themePath: "/admin/assets/module/authtree/tree_themes/",
                                theme: "auth-skin-default",
                                inputname: 'authority',
                                layfilter: 'lay-check-auth',
                                autowidth: true,
                                openall: true,
                                valueKey: "value",
                                childKey: "children",
                                collapseLeafNode: true,
                            });
                        } else {
                            layer.msg(res.msg, {icon: 2});
                        }
                    }, 'GET');

                    // 表单提交事件
                    form.on('submit(roleAuthorityFormSubmit)', function (d) {
                        layer.load(2);

                        //获取checked值
                        var checkedData = authtree.getChecked('#LAY-auth-tree-index');

                        //合并 checked button
                        var checkedJson = [];
                        var buttonChecked = {};
                        for(var i = 0; i < checkedData.length; i++) {
                            var checked = {};
                            var split = checkedData[i].split(":");
                            checked.menuId = split.length > 0 ? split[0] : null;

                            checked.roleId = data.id;
                            if(split.length > 1){
                                checked.button = split.length > 1 ? split[1] : null;
                                buttonChecked[checked.menuId] = buttonChecked[checked.menuId] == undefined ? checked.button : buttonChecked[checked.menuId] + "," + checked.button;
                            }
                            checkedJson.push(checked);
                        }

                        //菜单去重并写入合并 checked button
                        var result = [];
                        var obj = {};
                        for(var i =0; i<checkedJson.length; i++){
                            checkedJson[i].isChecked = true;
                            if(!obj[checkedJson[i].menuId]){
                                checkedJson[i].menuButton = buttonChecked[checkedJson[i].menuId] == undefined ? null : buttonChecked[checkedJson[i].menuId];
                                result.push(checkedJson[i]);
                                obj[checkedJson[i].menuId] = true;
                            }
                        }

                        admin.reqJson('user/admin/user/addRoleMenu', result, function (res) {
                            layer.closeAll('loading');
                            if (res.code == 200) {
                                layer.msg(res.msg, {icon: 1});
                                table.reload('roleTable');
                                layer.closeAll('page');
                            } else {
                                layer.msg(res.msg, {icon: 2});
                            }
                        }, 'POST');

                        return false;
                    });
                }
            });
        }

        // 模板下载
        $("#userBtnTemplate").click(function () {
            window.location.href = config.base + "user/admin/user/template";
        })

        // 导入excel
        $('#uploaderInput').on("change", function (e) {
            layer.load(2);
            var formData = new FormData();
            var files = e.target.files;
            let that = $(this);
            formData.append("file", files[0]);
            formData.append("name", files[0].name);//这个地方可以传递多个参数
            $.ajax({
                url: config.base + 'user/admin/user/importExcel',
                data: formData,
                headers: {Authorization: 'Bearer ' + config.getToken()},
                type: "POST",
                processData: false,
                contentType: false,
                success: function (res) {
                    layer.closeAll('loading');
                    if (res.code == 200) {
                        layer.msg(res.msg, {icon: 1});
                        layer.closeAll('page');
                        setTimeout(_ => {
                            location.reload()
                        }, 1000);
                    } else {
                        layer.msg(res.msg, {icon: 2});
                    }
                    that.val('');
                }
            });
        })

        // 导出excel
        $('#userBtnExport').click(function () {
            var publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCcLt6aJfWmRid+8Cuirv9Zi8sVfhSJ+pUkL7dC+M1yc+e6zr+PQj8sbl2jV5ZBhF4VwoIHWzFLoxNKSizukUNzumJi1KwhjmbASN2EVBKUhJwmx422oew9WCnZYE9+/T+xF87Diie3uQm+7cYVCpvlpqnf9zMBB0Js9zYjOPtP4wIDAQAB";
            var crypt = new JSEncrypt();
            crypt.setKey(publicKey);
            var token = "Bearer "+config.getToken();
            var tokenLeft = token.substring(0,50);
            var tokenRight = token.substring(50);
            var enc = crypt.encrypt(tokenLeft);
            var access_token = enc+tokenRight;
            access_token = access_token.replaceAll('+', '%2B');
            window.location.href = config.base + "user/admin/user/export?access_token=" + access_token;
        });

    });
</script>
